$(document).ready(function() {
	
	$('#createMemberCredentialDatePicker').datepicker();
	
	$('.getCredentials').click( function() {  
		window.location = '#signupSection';
		$('#signupSection').fadeIn();
		$('#userEmail').focus().keypress(function(event) {
    		if (((event.keyCode) == 13)) {
        		var userEmail = $('#userEmail').val(); 
        		getCreds(userEmail);
			}
		});
	});
	$('.TermsOfUseButton').click( function() {  
		$.modal.close();
		$('#TermsOfUse').modal({
			position: ["70px"],
			minHeight: "500px"			
		});
		$('.simplemodal-container').corner('10px');		
	});	
	$('.loginDialog').click( function() { 
		$('#loginDialog').modal({
			position: ["70px"],
			minHeight: "450px"
		});
		$('.simplemodal-container').corner('10px');
		$('#loginPass,#loginEmail').focus().keypress(function(event) {
    		if (((event.keyCode) == 13)) {
        		userLogin();
			}
		});
 		
	});
	$('.loginButton').click( function() {		
		userLogin();
	});				
	$('.PrivacyPolicyButton').click( function() {  
		$.modal.close();
		$('#PrivacyPolicy').modal({
			position: ["70px"],
			minHeight: "500px"			
		});
		$('.simplemodal-container').corner('10px');		
	});	
	$('.terminalModalButton').click( function() {  
		//$.modal.close();
		$('.simplemodal-container').css('display','block');
		$('#terminalModal').slideDown().show();	
		$('#simplemodal-overlay').show();
		$('#terminalModal').modal({
			minHeight: '500',
			minWidth: '80%',
			position: ["70px"],
			persist: 'true',
			onClose: function (dialog) {
				dialog.data.fadeOut(1000, function () {
					dialog.container.slideUp(1000, function () {
						dialog.overlay.fadeOut(1000, function () {
							$.modal.close(); // must call this!
						});
					});
				});
			},
			onOpen: function (dialog) {
				dialog.overlay.fadeIn();	
				dialog.data.show(function () {			
					dialog.container.slideDown(1000, function () {
					});
				});
			},
			closeHTML: "<a style='z-index:9999;' href='#' class='modalCloseImg' onClick='$(this).parent().slideUp(2000);' alt='Close' title='Close'><a>",

		});
		$('.simplemodal-container').corner('30px');		
		//$('#terminalModal').slideDown('slow');
	});
});

function userLogin() {
	var loginEmail = $('#loginEmail').val();
	var loginPass = $('#loginPass').val();
	$.ajax(
	    {
	        url: "/process.php?function=login&email="+loginEmail+"&pass="+loginPass+"",
	        type: "POST",
	        success: function(data) 
	        {
	        	scrollToAnchor('members');
	        	$.modal.close();
	        	window.location="/#members";
	        	location.reload();
	        	scrollToAnchor('members');
	        	//alert('success:' +data);
	        },
			error: function(data)
			{
	        	//alert('error!: '+data);
	        	$('#loginText').fadeOut();
	        	$('#loginText').html('We didn\'t recognize your email and/or password. Please try again!').fadeIn();
	        	if($('#loginEmail').val() == '') { $('#loginEmail').css('border-color','pink').focus(); } else { $('#loginEmail').css('border-color',''); $('#loginPass').focus(); }
	        	if($('#loginPass').val() == '') { $('#loginPass').css('border-color','pink'); } else { $('#loginPass').css('border-color',''); }     	
			},
			complete: function(data)
			{
				//alert('complete!:' +data);
			}	
		});	
		scrollToAnchor('members');
}

//Basic Email Validation
function validateEmail(email) { 
    var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    if(email.indexOf("@") > 0) {
    	return true;
    } else {
	    return false;
    }
} 			

//Animated Section Scroll
function scrollToAnchor(id){
	var aTag = $("#"+ id);
	$('html,body').animate({scrollTop: aTag.offset().top},'slow');
}

//Function that Sends Creds to Processing
function getCreds(email) {
	$('#signupMain').html('<img src="images/loader.gif" style="height:100px;">');
	if(!validateEmail(email)) { 
		setTimeout("$('#signupMessage').html('Your email address was not valid, please try again. Enter your email address and click \"I Agree\".')",500); 
		setTimeout("$('#signupMain').html($('#signupMainTemplate').html())",1000);
		$('#userEmail').focus();
	} else {
	    //alert('user:'+user+' | pass: '+pass+' | email: '+email);
		$.ajax(
		    {
		        url: "/process.php?function=newCred&email="+email,
		        type: "POST",
		        success: function(data) 
		        {
		        	$('#signupFooter').remove();
					$('#signupMessage').html('Success! We have emailed your credentials to '+email+'.');				        	
		        	$('#signupMain').html('<p><img src="images/complete.png" style="height:100px;"></p><p>In a few moments we will reload the site, and your new service icons will be available at the top of the page. If for some reason it doesn\'t reload, <a href="/">please click here.</a>');
		        	setTimeout('location.reload();',200);
		        	//alert(data);
		        },
				error: function()
				{
		        	$('#signupMain').html('<p>Something went terribly wrong. :(');
				}	
		});		
	}	
} 


//Function that Sends Creds to Processing
function credentialList() {
		$.ajax({
		        url: "/process.php?function=listCred",
		        type: "POST",
		        success: function(data) 
		        {
		        	$('#credentialListData').html(data);
		        },
				error: function()
				{
					alert('error!');
				}	
		});
}

//Function that Sends Creds to Processing
function credentialUserList() {
		$.ajax({
		        url: "/process.php?function=userListCred",
		        type: "POST",
		        success: function(data) 
		        {
		        	$('#credentialUserListData').html(data);
		        },
				error: function()
				{
					alert('error!');
				}	
		});
}

//Function that Sends Creds to Processing
function updateUserInfo(username,value,field) {
		$('#newEmail').hide();
		$('#newPass1').hide();
		$('#newPass2').hide();		
		$.ajax({
		        url: "/process.php?function=updateUserInfo&username="+username+"&value="+value+"&field="+field,
		        type: "POST",
		        success: function(data) 
		        {
		        	$('#updateEmailButton').hide();
		        	$('#updateEmailText').html('Updated Successfully. Thank you!<br /><br />The page will reload shortly to reflect the change.');
		        	setTimeout(location.reload(),2000);
		        	$('#updatePassButton').hide();
		        	$('#updatePassText').html('Updated Successfully. Thank you!<br /><br />The page will reload shortly to reflect the change.');
		        	setTimeout(location.reload(),2000);		        	
		        },
				error: function(data)
				{
					$('#newEmail').fadeIn().css('border-color','pink').focus();
					$('#updateEmailText').html('There was a problem, please try again.');
					//alert('error!:'+date);
				}	
		});
}
function createMemberCredentialButton(){
	$.modal.close();
	$('#createMemberCredentialModal').modal({
		position: ["70px"],
		minHeight: "500px"			
	});
	$('.simplemodal-container').corner('10px');	
}

//Function that creates member credential
function createMemberCredential(expiration) {
		$('#createMemberCredentialText,#createMemberCredentialText2,#createMemberCredentialButton').hide();
		$('#createMemberCredentialLoader').show();
		$.ajax({
		        url: "/process.php?function=createMemberCredential&expiration="+expiration,
		        type: "POST",
		        success: function(data) 
		        {
		        	$('#createMemberCredentialLoader').hide();
		        	$('#createMemberCredentialText').html('<br />Credentials created successfully!'); 
		        	$('#createMemberCredentialText2').html('<br />Username: <span style=font-size:2em;font-weight:bold;background-color:#ffffcc;color:black;>a5sd4a</span> &nbsp;&nbsp;&nbsp;&nbsp;Password: <span style=font-size:2em;font-weight:bold;background-color:#ffffcc;color:black;>1234</span><br /><br />Expires on '+expiration);
		        	$('#createMemberCredentialText,#createMemberCredentialText2').show();
 		        },
				error: function(data)
				{
					alert('error: '+data)
				}	
		});
}


//Function that creates member credential
function destroyAll() {
		$('#destroyAllText,#destroyAllButton').hide();
		$('#destroyAllLoader').show();
		$.ajax({
		        url: "/process.php?function=destroyAllCredentials",
		        type: "POST",
		        success: function(data) 
		        {
		        	$('#destroyAllLoader').hide();
		        	$('#destroyAllText').html('Sucessfully destroyed all of your credentials.<br /><br />Reloading page to reflect changes.');
		        	location.reload();
		        	//alert('success: '+data);
 		        },
				error: function(data)
				{
					alert('error: '+data);
				}	
		});
}